package com.kfm.company.interceptor;

import com.kfm.company.model.bean.AccessInfo;
import com.kfm.company.model.bean.AccessList;
import com.kfm.company.util.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class RequestManyInterceptor implements HandlerInterceptor {

    @Autowired
    private AccessList accessList;

    @Autowired
    private AccessIPInterceptor accessIPInterceptor;

    @Value("${wx.request_count}")
    private Integer max;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = IPUtil.getIpAddress(request);
        Map<String, AccessInfo> accessInfoMap = accessList.getAccessInfoMap();
        AccessInfo accessInfo = accessInfoMap.get(ip);
        long current = System.currentTimeMillis();
        if (accessInfo == null) {
            // 第一次访问
            AccessInfo accessInfo1 = new AccessInfo();
            accessInfo1.setCount(1);
            accessInfo1.setLast(current);
            accessInfoMap.put(ip, accessInfo1);
            return true;
        } else if (current - accessInfo.getLast() > 1000) {
            accessInfo.setLast(current);
            accessInfo.setCount(1);
            return true;
        } else {
            // 一秒之内访问的 判断访问的次数
            int count = accessInfo.getCount() + 1;
            accessInfo.setLast(current);
            if (count >= max) {
                accessIPInterceptor.blackIPList.add(ip);
                response.sendRedirect(request.getContextPath() + "/error");
                return false;
            } else {
                accessInfo.setCount(count);
                return true;
            }
        }
    }
}
